package 生产者消费者模型;

import java.util.LinkedList;
import java.util.concurrent.locks.ReentrantLock;

public class MessageQueue {
    //存放消息的容器-->双端队列
    private LinkedList<Message> list = new LinkedList<>();
    //容量
    private int capacity;

    public MessageQueue(int capacity) {
        this.capacity = capacity;
    }

    //获取信息
    public Message take(){
            synchronized (list) {
                while(list.isEmpty()) {
                    try {
                        System.out.println("队列为空,消费者等待");
                        list.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                Message message = list.removeFirst();
                System.out.println(Thread.currentThread() +"已消费消息 " + message);
                list.notifyAll();
                return message;
            }
    }

    //存放信息
    public void put(Message message){
        synchronized (list) {
            while(list.size()==capacity) {
                try {
                    System.out.println("队列已满,生产者等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.addLast(message);
            System.out.println(Thread.currentThread() +"已生产信息 "+ message);
            list.notifyAll();
        }
    }
}